import { ElMessage } from 'element-plus';
import { createRouter, createWebHistory } from 'vue-router';

import { useUserStore } from '@/stores';

const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_BASE_URL),
  routes: [
    {
      path: '/',
      children: [
        {
          path: '',
          name: 'index',
          component: () => import('@/layout/LayoutView.vue'),
        },
      ],
    },
    {
      path: '/404',
      name: '404',
      component: () => import('@/common/views/404.vue'),
      meta: {
        key: '404',
      },
    },
  ],
});

//路由白名单
const whiteList = ['/login', '/404', '/401', '/register'];
router.beforeEach((to, from, next) => {
  const userState = useUserStore();
  const token = userState.userInfo;
  //页面级别的权限配置
  if (!checkLogin(token) && !whiteList.includes(to.path)) {
    userState.removeInfo();
    ElMessage.error('请先登录');
    next('/login');
    return;
  } else {
    if (!router.hasRoute(to.name || '')) {
      next('/404');
    } else {
      next();
    }
  }
});
export default router;
export const checkLogin = (token: string) => {
  if (token && token.length > 10) {
    return true;
  } else {
    return false;
  }
};
